<?php
namespace app\common\component\lottery_3_log;

use app\common\model\Lottery3Log;

class Lottery3LogService {
	public function makeLog($user_id, $price) {
		$data['user_id'] = $user_id;
		$data['status'] = 3;
		$data['price'] = $price;
		$data['interest'] = 0;
		$data['last_get_interest_time'] = $data['start_time'] = time();
		$data['end_time'] = $data['start_time'] + 10 * 24 * 60 * 60;

		return $this -> create($data);
	}

	public function create($data) {
		$lottery3Log = new Lottery3Log($data);

    	if($lottery3Log -> save()) {
    		return [
    			'code' => 0,
    			'message' => '鹅蛋购买成功!',
    			'data' => [
    				'lottery_3_log' => $lottery3Log
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '鹅蛋购买失败!'
		];
	}

	public function getInterest() {
		$user_id = \think\Session::get('user_id');
		$selectLottery3Log = Lottery3Log::where('status in(3, 4) AND user_id = ' . $user_id) -> order('lottery_3_log_id ASC') -> select();
		$numCacheStr = 'lottery3LogNum_' . $user_id;

		if(!empty($selectLottery3Log)) {
			$num = \think\Cache::get($numCacheStr);
			if(!$num) {
				$num = 0;
			}
			$price = 0;

			foreach($selectLottery3Log as $lottery3Log) {
				switch($lottery3Log -> getData('status')) {
					case 3:
						$remainingDays = countDays($lottery3Log -> last_get_interest_time);
						$totalDays = countDays($lottery3Log -> last_get_interest_time, $lottery3Log -> end_time);

						if($remainingDays >= $totalDays) {
							$num += $lottery3Log -> price;

							$lottery3Log -> status = 4;

							$interest = $lottery3Log -> price * 0.13 * $totalDays;

							if($num >= 100) {
								$t = floor($num / 100);
								$interest += $t * 3;

								$num -= $t * 100;
								if($num <= 0) {
									$num = 0;
								}
							}

							\think\Cache::set($numCacheStr, $num);
						} else {
							$interest = $lottery3Log -> price * 0.13 * $remainingDays;
						}

						$interest = round($interest, 2);
						if($interest != $lottery3Log -> interest) {
							$lottery3Log -> interest = $interest;
							$lottery3Log -> save();
						}
						break;
				}

				$price += $lottery3Log -> interest;
			}

			return [
				'code' => 0,
				'data' => [
					'price' => $price
				]
			];
		}

		return [
			'code' => 0,
			'data' => [
				'price' => 0
			]
		];
	}
}
?>